package com.noodles.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.noodles.mall.entity.Role;
import com.noodles.mall.mapper.RoleMapper;
import com.noodles.mall.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.noodles.mall.vo.PageVo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
;import java.util.ArrayList;
import java.util.List;

/** 角色 **/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService, InitializingBean {

    @Override
    public void afterPropertiesSet(){
        INTEGER_ROLE_MAP.clear();
        STRING_ROLE_MAP.clear();
        super.list().forEach(role ->{
            INTEGER_ROLE_MAP.put(role.getId(),role);
            STRING_ROLE_MAP.put(role.getName(),role);
        });
    }

    /** 增加 **/
    public boolean insert(Role role){
        if(super.save(role)){
            afterPropertiesSet();
            return true;
        }else return false;
    }

    /** 修改: 根据id修改所有 **/
    public boolean updateById(Role role){
        if(super.updateById(role)){
            afterPropertiesSet();
            return true;
        }else return false;
    }

    /** 查询单个: name **/
    public Role selectOne(String name){
        return STRING_ROLE_MAP.get(name);
    }

    /** 查询列表: 无 **/
    public List<Role> selectList(){
        ArrayList<Role> list=new ArrayList<>();
        INTEGER_ROLE_MAP.values().forEach(role -> list.add(role));
        return list;
    }

    /** 分页查询: wrapper **/
    public PageVo selectPage(Long current, Long size, LambdaQueryWrapper<Role> wrapper){
        Page<Role> page = super.page(new Page<>(current, size), wrapper);
        return PageVo.getPageVo(page);
    }

    /** 分页查询: 无 **/
    public PageVo selectPage(Long current, Long size){
        LambdaQueryWrapper<Role> wrapper=new QueryWrapper<Role>().lambda()
                .orderByDesc(Role::getCreatedTime);
        return selectPage(current,size,wrapper);
    }

    /** 分页查询: word--like name or name_rn **/
    public PageVo selectPage(Long current, Long size, String word){
        LambdaQueryWrapper<Role> wrapper=new QueryWrapper<Role>().lambda()
                .like(Role::getName,word).or()
                .like(Role::getNameRn,word)
                .orderByDesc(Role::getCreatedTime);
        return selectPage(current,size,wrapper);
    }


}
